//--------------------------------------------------------------------------
// 
//  Copyright (c) Chili Software.  All rights reserved. 
// 
//  File: ObjectReaderSchema.cs
//
//  Description: The schema (column name, column index pair) for an OR.
// 
//--------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Chili.Opf3.Mapping;

namespace Chili.Opf3
{
	/// <summary>
	/// This class holds the schema (column name, column index pair) for an <see cref="ObjectReader{T}">ObjectReader</see>.
	/// </summary>
	internal sealed class ObjectReaderSchema
	{
		private int[] _columnIndices;

		/// <summary>
		/// Creates an instance of the <see cref="ObjectReaderSchema">ObjectReaderSchema Class</see>.
		/// </summary>
		/// <param name="dataReader">The data reader used to create the schema. This data reader is set given by the <see cref="ObjectReader{T}">ObjectReader</see>.</param>
		/// <param name="type">The type of the persistent object.</param>
		public ObjectReaderSchema(IDataReader dataReader, Type type)
		{
			TypeMapping mapping = TypeMapping.GetTypeMapping(type);
			int count = mapping.Members.Count;

			// Create the indices array.
			_columnIndices = new int[count];

			// Build the lower names arrey.
			string[] lowerNames = new string[count];
			IMemberInfoCollection members = mapping.Members;
			for (int i = 0; i < count; i++)
			{
				lowerNames[i] = members[i].FieldAttribute.FieldName.ToLower();
			}

			// Get the column indices in the result set.
			for (int i = 0; i < dataReader.FieldCount; i++)
			{
				string name = dataReader.GetName(i).ToLower();

				for (int j = 0; j < count; j++)
				{
					if (lowerNames[j] == name)
					{
						_columnIndices[j] = i + 1;
						break;
					}
				}
			}
		}

		/// <summary>
		/// Returns the index of the given member index or -1 if the column hasn't been found.
		/// </summary>
		/// <param name="memberIndex">Index of hte member.</param>
		/// <returns>Index of the column or -1 if not found.</returns>
		public int IndexOfColumn(int memberIndex)
		{
			return _columnIndices[memberIndex] - 1;
		}
	}
}
